/**
 * @describe WX API
 * @author 游金宇(KM)
 * @date 2022-12-29 14:19:55
 */

import { error, log } from "cc";
import { H5API } from "../H5API";



export class WXAPI extends H5API {

    protected override netWorkStatusListener() {
        wx.onNetworkStatusChange((res) => {
            res.isConnected ? this.online() : this.offline()
        })
    }

    override getEnvironmentAsync(): string {
        const accountInfo = wx.getAccountInfoSync();
        // develop:开发版、trial:体验版、release:正式版
        return accountInfo.miniProgram.envVersion;
    }

    override getLaunchOptionsSync(): WechatMinigame.LaunchOptionsGame {
        return wx.getLaunchOptionsSync();
    }


    override getSetting(): Promise<boolean> {
        return new Promise((resolve, reject) => {
            wx.getPrivacySetting({
                success(res) {
                    if (res.needAuthorization) {
                        reject();
                        log('用户隐私已授权');
                    } else {
                        log('用户隐私未授权');
                        resolve(res.needAuthorization);
                    }

                },
            });
        });
    }

    override getSystemInfo(): Promise<WechatMinigame.SystemInfo> {
        return new Promise((resolve, reject) => {
            wx.getSystemInfo({
                success: (res) => {
                    const { global } = this.cat.store
                    global.pixelRatio = res.pixelRatio
                    global.titleBarHeight = res.statusBarHeight
                    resolve(res)
                },
                fail: (err) => {
                    error(err)
                    reject(err)
                }
            })
        })
    }

    override getLoginCode(): Promise<string> {
        return new Promise((resolve, reject) => {
            wx.login({
                provider: 'weixin',
                success: loginRes => {
                    this.cat.store.login.code = loginRes.code
                    resolve(loginRes.code);

                },
            });
        });
    }

    override async serverLogin(): Promise<void> {
        const { login } = this.cat.store
        await this.getLoginCode()
        // await api.login.login(new web.v1.LoginRequest({ code: login.code }))
    }

    override getUserInfo(): Promise<void> {
        return new Promise((resolve, reject) => {
            wx.getUserInfo({
                success: (res) => {
                    log(res.userInfo)
                    const { user } = this.cat.store
                    // user.avatar = res.userInfo.avatarUrl
                    // user.userName = res.userInfo.nickName
                    resolve();
                },
                fail: (err) => {
                    this.cat.gui.showToast({ title: err.errMsg })
                    error(err.errMsg)
                    reject()
                }
            });
        })
    }

    /**跳转小程序 */
    override navigateToMiniProgram(): Promise<void> {
        console.error('暂未实现方法')
        return Promise.reject();
    }

    /**获取appId */
    override getAppId() {
        console.error('暂未实现方法')
        return wx.getAccountInfoSync().miniProgram.appId
    }

    override authorize(): Promise<void> {
        // return new Promise((resolve, reject) => {
        //     // wx.requirePrivacyAuthorize({
        //     //     success: () => {
        //     //         // 用户同意授权
        //     //         resolve()
        //     //     },
        //     //     fail: () => {
        //     //         // this.authorize()
        //     //     }, // 用户拒绝授权
        //     //     complete: () => { }
        //     // })
        // })
        return new Promise((resolve, reject) => {
            //用户未授权的话，全屏覆盖一个按钮，用户点击任意地方都会触发onTap()，弹出授权界面
            let sysInfo = wx.getSystemInfoSync();
            let width: number = sysInfo.screenWidth;
            let height: number = sysInfo.screenHeight;
            let button = wx.createUserInfoButton({
                type: 'text',
                text: '', //不显示文字
                style: {
                    left: 0,
                    top: 0,
                    width: width,
                    height: height,
                    lineHeight: 40,
                    backgroundColor: '#00000000', //设置按钮透明
                    color: '#ffffff',
                    textAlign: 'center',
                    fontSize: 16,
                    borderRadius: 4,
                    borderColor: '#00000000',
                    borderWidth: 0,
                },
                withCredentials: false,
            });
            button.onTap(res => {
                if (res.userInfo) {
                    log('用户授权进入游戏', res);
                    // 资源加载完成
                    button.destroy(); //此时删除按钮
                    resolve()
                } //说明用户点击 不允许授权的按钮
                else {
                    log('用户拒绝授权');
                    //用户不允许授权的话不删除按钮，阻止进入游戏
                }
            });
        })
    }

    override showShareMenu() {
        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline'],
        })
    }

    /**分享app */
    override onShareAppMessage(option: ShareOption) {
        return wx.onShareAppMessage(() => {
            return option;
        })
    }
    /**分享朋友圈 */
    override onShareTimeline(option: ShareOption) {
        return wx.onShareTimeline(() => {
            return option;
        })
    }

}
